package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchArticleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchArticleLogic {
	return &SearchArticleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchArticleLogic) SearchArticle(in *Article.SearchArticleRequest) (*Article.GetArticleListResponse, error) {
	var searchArticleDto models.SearchArticleDto
	copier.Copy(&searchArticleDto, in)
	var articleVoList []models.ArticleListVo
	db := models.Db.Model(new(models.ArticleListVo)).
		Table("t_article a").
		Select("a.*,c.category_name as category_name,u.username as username").
		Joins("left join t_category c on a.category_id = c.id").
		Joins("left join sys_user u on a.user_id = u.id")
	if searchArticleDto.ArticleTitle != "" {
		db.Where("a.article_title like ?", "%"+searchArticleDto.ArticleTitle+"%")
	}
	if searchArticleDto.CategoryId != 0 {
		db.Where("a.category_id = ?", searchArticleDto.CategoryId)
	}
	if searchArticleDto.Status.Valid {
		db.Where("a.status = ?", searchArticleDto.Status.Int64)
	}
	if searchArticleDto.IsTop.Valid {
		db.Where("a.is_top = ?", searchArticleDto.IsTop.Int64)
	}
	db.Find(&articleVoList)

	for i, v := range articleVoList {
		var tagsName []string
		models.Db.Model(new(models.ArticleTag)).
			Distinct("t.tag_name").
			Table("t_article_tag at").
			Select("t.tag_name").
			Joins("left join t_tag t on at.tag_id = t.id").
			Where("at.article_id = ?", v.Id).
			Find(&tagsName)
		articleVoList[i].TagsName = tagsName
	}
	var articleListVoResponse []*Article.ArticleListVo
	copier.Copy(&articleListVoResponse, &articleVoList)
	for i, v := range articleVoList {
		articleListVoResponse[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
	}
	return &Article.GetArticleListResponse{
		Code: int64(HttpCode.SUCCESS),
		Data: articleListVoResponse,
	}, nil
}
